#  :20 0000 00 007016F100000000000000000000000000000000000000000000000000000000 69
#  : 开始 20 字节长度  0000 地址偏移  00 Data Record   0070 - 0000 数据   69 校验位
#  intel hex 功能码
# ‘00’ Data Record
# ‘01’ End of File Record
# ‘02’ Extended Segment Address Record
# ‘03’ Start Segment Address Record
# ‘04’ Extended Linear Address Record
# ‘05’ Start Linear Address Record‘00’ Data Record
# ‘01’ End of File Record
# ‘02’ Extended Segment Address Record
# ‘03’ Start Segment Address Record
# ‘04’ Extended Linear Address Record
# ‘05’ Start Linear Address Record

# pyinstaller -F get_hex.py  打包成exe ，便于在ccs中调用
import time



class Deal_Intel_HexFile(object):
    def __init__(self,file_name):
        self.file_name = file_name
        self.file = None
        self.f_write = None
        self.times = 0

    # 读取文件
    def read_file(self):
        try:
            self.file = open(self.file_name)
        except Exception as e:
            print("文件读取失败："+e)

    # 处理每行数据
    def deal_line(self):
        self.read_file()
        if self.file == None:
            print("文件读取失败")
            return
        while 1:
        # for i in range(100):
            line = self.file.readline()
            if not line:
                if self.f_write != None:
                    self.f_write.close()
                break
            if(line[7:9] == "04"):
                time.sleep(1)
                self.write_data(None,0)
            else:
                if self.f_write != None:
                    # print(str(line[1:3]))
                    lenth = int(str(line[1:3]),16)*2
                    self.write_data(line[9:9+lenth])

        print("get {} hex file".format(self.times))


    def write_data(self,data,write=1):
        if write == 0:
            if self.f_write != None:
                self.f_write.close()
            self.f_write = open('{}.txt'.format(self.times), 'w')
            self.times+=1
        else:
            if(len(data)%4 !=0):
                print("数据不是4的倍数")
            for i in range(0,len(data),4):
                i += 4
                self.f_write.write('0x'+data[i-4:i]+'\n')






if __name__ == '__main__':
    d = Deal_Intel_HexFile("DspProgram.hex")
    d.deal_line()












